<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Book;
use App\Models\BookDraft;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use function App\Helpers\createdGuid;
use function App\Helpers\errorMsg;
use function App\Helpers\successMsg;

class ChapterController extends Controller
{
    //
    //获取书籍列表
    public function GetBookList(Request $request)
    {
        $params = $request->all();
        $table_suffix = !empty($params->suffix)?$params->suffix:date("Y");
        $bookObj = (new Book($table_suffix));
        $res = $bookObj->getTest();
        var_dump($res);
    }
    //获取 书籍 章节列表
    public function index(Request $request)
    {
        $where = [];
        $book_uni_code = $request->book_uni_code ?? null;
        $is_vip = $request->is_vip ?? null;
        $free = $request->free ?? null;
        $name = $request->name ?? null;
        if(empty($book_uni_code)) return errorMsg(-1,"书籍uni_code不能为空!!!");
        if(!is_null($is_vip)) $where[] = ['is_vip','=',$is_vip];
        if(!is_null($free) && $free == 0){
            $where[] = ['free','=',0];
        }else if(!is_null($free) && $free == 1){
            $where[] = ['free','>',0];
        }
        if(!empty($name)) $where[] = ['name','like',$name.'%'];
        $year = Book::query()->where('uni_code',$book_uni_code)->value('year');
        $chapter_table = Config::get("site.chapter_table").$year;
        $page = $this->executePage($request);
        $data = DB::table($chapter_table)
            ->where($where)
            ->limit($page['per_page'])
            ->offset($page['offset'])
            ->orderBy("index","desc")
            ->get();
        $total = DB::table($chapter_table)->where($where)->count("id");
        $data = [
            'page' => $page['page'],
            'per_page' => $page['per_page'],
            'total' => $total,
            'data' => $data,
        ];
        return successMsg($data);
    }

    //章节内容添加
    public function insert(Request $request)
    {
        $params = $request->all();
        $book = DB::table("book")->where('uni_code',$params['book_uni_code'])->first();
        $chapter_table = Config::get("site.chapter_table").$book->year;
        $content_table = Config::get("site.content_table").$book->year;
        $chapter_data = [
            'book_id' => $book->id,
            'book_uni_code' => $book->uni_code,
            'uni_code' => createdGuid(),
            'name' => $params['name'],
            'word' => mb_strlen($params['content']),
            'free' => $params['free'],
            'year' => date("Y"),
            'month' => date("m"),
            'created_at' => date("Y-m-d H:i:s"),
        ];
        $content_data = [
            'content' => $params['content'],
            'created_at' => date("Y-m-d H:i:s"),
        ];
        DB::beginTransaction();
        try {
            $chapter_max_index = DB::table($chapter_table)->where('book_id',$book->id)->max('index') ?? 0;
            $chapter_data['index'] = $chapter_max_index > 0 ? $chapter_max_index + 1 : $chapter_max_index;
            $chapter_id = DB::table($chapter_table)->insertGetId($chapter_data);
            $content_data['chapter_id'] = $chapter_id;
            $content_insert = DB::table($content_table)->insert($content_data);
            $book_word = $book->word+mb_strlen($params['content']);
            $book_insert = Book::query()->where('id',$book->id)->update(['word' => $book_word]);
            if($chapter_id && $content_insert && $book_insert){
                DB::commit();
                return successMsg();
            }else{
                DB::rollBack();
                return errorMsg(-1,'数据发表失败!!!');
            }
        }catch (\Exception $e){
            DB::rollBack();
            return errorMsg(-1,'数据发表失败!!!');
        }
    }
    //章节内容 存到草稿箱里 (此功能应当为 作者后台才有的)
//    public function draft(Request $request)
//    {
//        $params = $request->all();
//        if(empty($params['book_uni_code']) || empty($params['name'])) return errorMsg(-1,"书籍编码 和章节名称 不能为空!!!");
//        $book = DB::table("book")->where('uni_code',$params['book_uni_code'])->first();
//        $data = [
//            'author_id' => $params['author_id'] ?? 0,
//            'book_uni_code' => $params['book_uni_code'],
//            'book_name' => $book->name,
//            'chapter_name' => $params['name'],
//            'value' => serialize($params),
//            'created_at' => date("Y-m-d H:i:s",time())
//        ];
//        BookDraft::query()->insert($data);
//        return successMsg();
//    }
    //章节 内容 更新
    public function update(Request $request)
    {
        $params = $request->all();
        $year = DB::table("book")->where('uni_code',$params['book_uni_code'])->value("year");
        $chapter_table = Config::get("site.chapter_table").$year;
        $content_table = Config::get("site.content_table").$year;
        $chapter = DB::table($chapter_table)->where('uni_code',$params['chapter_uni_code'])->first();
        $chapter_data = [
            'name' => $params['name'],
            'is_vip' => $params['is_vip'],
            'free' => $params['free'],
            'word' => mb_strlen($params['content']),
        ];
        $content_data = [
            'content' => $params['content'],
        ];
        DB::table($chapter_table)->where('id',$chapter->id)->update($chapter_data);
        DB::table($content_table)->where('chapter_id',$chapter->id)->update($content_data);
        return successMsg();
    }
    //章节 内容 详情
    public function detail(Request $request)
    {
        $params = $request->all();
        $field = [
//            'chapter.id as chapter_id',
            'chapter.book_uni_code',
            'chapter.uni_code as chapter_uni_code',
            'chapter.is_vip',
            'chapter.free',
            'chapter.name',
            'content.content',
        ];
        $year = DB::table("book")->where('uni_code',$params['book_uni_code'])->value("year");
        $chapter_table = Config::get("site.chapter_table").$year;
        $content_table = Config::get("site.content_table").$year;
        $data = DB::table($chapter_table,"chapter")
            ->leftJoin($content_table." as content","chapter.id","=","content.chapter_id")
            ->select($field)
            ->first();
        return successMsg($data);
    }
}
